// ============================== 导入依赖 ============================== //
import '@babylonjs/loaders'
import { Engine, Scene, ArcRotateCamera, Vector3, Color3, SceneLoader, MeshBuilder, StandardMaterial } from '@babylonjs/core'
import CORE from '@/CORE'
import state from './state'
import API from './API'
// ============================== 导出仓库 ============================== //

export default {
  props: {
    type: { type: String, required: true }, // 组态类型
  },
  data() {
    return {
      ...state(),
    }
  },
  watch: {
    type(type) {
      this.modelTypeChange(type)
    },
  },
  methods: {
    /**
     * @function 组态类型改变
     * @param {Number} val -模型类型
     */
    modelTypeChange(val) {
      API.get3dModelLatest({ configType: +val }).then((res) => {
        const _3dfileUrl = CORE._3Dfile(res.modelSubUrl)
        const _3DfileName = _3dfileUrl.split('?')[0].split('/').reverse()[0]
        const _3DfileRootUrl = _3dfileUrl.split(_3DfileName)[0]

        this.scene = this.createScene(this.engine, _3DfileRootUrl, _3DfileName)
        this.engine.runRenderLoop(() => { this.scene.render() })
      })
    },
    /**
     * @function 创建场景
     * @param {*} engine -引擎
     * @param {*} rootUrl
     * @param {*} sceneFilename
     */
    createScene(engine, rootUrl, sceneFilename) {
      if (!engine || !rootUrl || !sceneFilename) return

      engine.clear()
      const scene = new Scene(engine)

      scene.createDefaultLight()

      const skyBox = MeshBuilder.CreateBox('skyBox', { size: 1000 }, scene)
      const skyBoxMaterial = new StandardMaterial('skyMaterial', scene)
      skyBoxMaterial.backFaceCulling = false
      skyBoxMaterial.emissiveColor = new Color3(1, 1, 1)
      skyBox.material = skyBoxMaterial

      const arcRotateCamera = new ArcRotateCamera('arc-rotate-camera', 3.138, 1.12, 20, new Vector3(0, 0, 0), scene)
      arcRotateCamera.upperBetaLimit = Math.PI / 2
      arcRotateCamera.allowUpsideDown = false
      arcRotateCamera.lowerRadiusLimit = 5
      arcRotateCamera.upperRadiusLimit = 40
      arcRotateCamera.attachControl(engine.getRenderingCanvas(), true)

      SceneLoader.Append(rootUrl, sceneFilename, scene, () => {
        window.console.log('模型加载成功!')
      })

      return scene
    },
    resize() {
      this.engine.resize()
    },
  },
  mounted() {
    this.engine = new Engine(document.getElementById('3dModelSettingCanvas'), true)
    this.modelTypeChange(this.type)
    window.addEventListener('resize', this.resize)
  },
  destroyed() {
    window.removeEventListener('resize', this.resize)
  },
}
